#include "file_utils.h"
#include <fstream>
#include <filesystem>

namespace fs = std::filesystem;

using namespace std;

_TRT_INFER_BEGIN
namespace FileUtils
{

    bool save_file(const std::string &file, const void *data, size_t length)
    {

        FILE *f = fopen(file.c_str(), "wb");
        if (!f)
            return false;

        if (data && length > 0)
        {
            if (fwrite(data, 1, length, f) != length)
            {
                fclose(f);
                return false;
            }
        }
        fclose(f);
        return true;
    }

    vector<unsigned char> load_file(const string &file)
    {
        ifstream in(file, ios::in | ios::binary);
        if (!in.is_open())
            return {};

        in.seekg(0, ios::end);
        size_t length = in.tellg();

        std::vector<uint8_t> data;
        if (length > 0)
        {
            in.seekg(0, ios::beg);
            data.resize(length);

            in.read((char *)&data[0], length);
        }
        in.close();
        return data;
    }

    std::string concat_path(const std::string &dir, const std::string &file)
    {
        return (fs::path(dir) / fs::path(file)).string();
    }

    bool is_file_exist(const std::string &file)
    {
        return fs::exists(file);
    }

} // namespace FileUtils

_TRT_INFER_END